package com.wu.components;

import com.wu.flandre_common.entity.RpcRequest;
import com.wu.flandre_common.entity.RpcResponse;
import com.wu.flandre_common.property.Constants;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * DispatcherHandle <br/>
 * Flandre引擎 事件调度中心
 *
 * @author 50816 <br/>
 * @date 2019/12/22 12:02 <br/>
 */
@Slf4j
public class NettyServerHandle extends ChannelInboundHandlerAdapter {
    /**
     * 接受client发送的消息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest) msg;
        EventDispacher dispacher = new EventDispacher();
        RpcResponse response = dispacher.dispache(ctx,request);
        System.out.println(response.toString());
        ctx.writeAndFlush(response);
    }

    /**
     * 通知处理器最后的channelRead()是当前批处理中的最后一条消息时调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * 读操作时捕获到异常时调用
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("执行任务时异常:" + cause.getMessage());
        RpcResponse<String> response = new RpcResponse<>();
        response.setStatus(Constants.NETTY_ERROR);
        response.setMsg("引擎发生异常");
        ctx.channel().writeAndFlush(response);
    }

    /**
     * 客户端去和服务端连接成功时触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Flandre客户端连接成功,IP address:" + ctx.channel().remoteAddress());
    }

}
